<script lang="ts" setup>
import type { AttriButesType, StateType } from './types';
import Draggable from 'vuedraggable';

import { computed } from 'vue';
import { useRoute } from 'vue-router';
import { $t } from '@vben/locales';
import { Page, useVbenDrawer, useVbenModal,z } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';

import { useTitle } from '@vueuse/core';
import {
  Button,
  Card,
  Divider,
  Input,
  message,
  Select,
  SelectOption,
  Space,
  TabPane,
  Tabs,
  TreeSelect,
  Upload,
  
} from 'ant-design-vue';
import ImgTextGroup from '#/components/ImgTextGroup';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';

import { useVbenForm } from '#/adapter/form';
import { getArticleInfo, postArticle, putArticle } from '#/api/portal/article';


import { getPage_news as getCarModelsByCategory } from '#/api/portal/carmodel'
import { getYears } from '#/api/admin/year';
import { getYears as getConfigs } from '#/api/admin/config';
import Icon from '#/components/Icons';
import { usePreferencesStore } from '#/store';
import { mergeObjects } from '#/utils';

import { AttributesDrawerView, AttributesModalView } from './components';

const route = useRoute();
const copyFrom = Number(route.query.copyFrom) || -1;

const { setTabTitle, closeCurrentTab } = useTabs();

const index: any = computed(() => {
  return route.params?.id ?? -1;
});
const code: any = computed(() => {
  return route.params?.code ?? 'article';
});
const VNodes = defineComponent({
  props: {
    vnodes: {
      type: Object,
      required: true,
    },
  },
  render() {
    return this.vnodes;
  },
});
const inputRef = ref();
const name = ref();
const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
const year =ref();
const config =ref();
const pageTitle =
  Number.parseInt(index.value, 10) === 0
    ? `新增${routeTitle}`
    : `${routeTitle}ID:${index.value}`;
setTabTitle(pageTitle);
useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    post_status:'',
    post_title: '',
    // slug:'',
    categories: [],
    thumbnails:[],
    more: {
      thumbnail: '',
    },
  },
  attributes: {
    module: [],
    parameter: [],
    spec: [],
  },
  tags: [],
  moduleName: '',
  categoriesTree: [],
  modules: [],
  listThemeFiles: [],
  articleThemeFiles: [],
});

const carModelOptions = ref([]);

const onCategoryChange = async (categoryId) => {
  if (!categoryId) {
    carModelOptions.value = [];
    return;
  }

  const { data } = await getCarModelsByCategory({ category_id: categoryId });
  carModelOptions.value = (data?.list || []).map(item => ({
    label: item.category_name+' '+item.name,
    value: item.id,
  }));

  console.log(carModelOptions.value);
};

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  resetButtonOptions: {
    show: false,
  },
  commonConfig: {
    labelWidth: 150,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
      
    },
  
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
         //&& values.categories.length > 0
          disabled.value = !(values.post_title );
        //  state.form.slug = values.slug;
          state.form.more.thumbnail = values.thumbnail;
          state.form.categories = values.categories;
          state.form.post_content = values.post_content;
          state.form.post_status = values.post_status;
          state.form.post_title = values.post_title;
          state.form.thumbnails = values.thumbnails;
          state.form.year = values.year;
          state.form.config = values.config;
          state.form.smart =values.smart;
          state.form.highlights = values.highlights;
          state.form.more.Engine = values.Engine;
          state.form.more.Ground = values.Ground;
          state.form.more.Passenger = values.Passenger;
          state.form.more.Drive = values.Drive;
          state.form.more.Features = values.Features;
          state.form.car_model = values.car_model;
           
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'post_status',
          'post_title',
          // 'slug',
          'categories',
          'thumbnails',
          'post_content',
          'year',
          'config',
          'smart',
          'Engine',
          'Ground',
          'Passenger',
          'Drive',
          'Features',
          'car_model',
          'highlights'
        ],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'post_title',
      label: $t('page.common.Title'),
      rules: 'required',
    },
    //  {
    //   component: 'Input',
    //   defaultValue: '',
    //    componentProps: {
    //     placeholder: '请输入',
    //   },
    //   fieldName: 'slug',
    //   label: `${routeTitle}别名`,
    //   rules: z.string({
    //       required_error: '别名不能为空',
    //       invalid_type_error: '别名格式不正确',
    //     })
    //     .min(1, '别名不能为空')
    //     .max(50, '不能超出50个字符')
    //     .regex(/^[\u4e00-\u9fa5\w-]+$/, '只能包含中英文、数字、_或-')
    //       },
    {
      component: 'RadioGroup',
      componentProps: {
        options: [
          {
            label: 'Publish',
            value: 1,
          },
          {
            label: 'Trash',
            value:  0,
          },
          
        ],
      },
      fieldName: 'post_status',
      rules: 'required', 
      label: $t('page.common.Status'),
    },
    {
      component: 'TreeSelect',
      fieldName: 'categories',
      label: $t('page.common.Car Series'),
      rules: 'required',
      componentProps: {
        onChange: onCategoryChange, // 👈 监听选中变化
        placeholder: $t('page.common.Please Select')+' '+$t('page.common.Car Series'),
      },
    },
     {
      component: 'Select',
      fieldName: 'car_model',
      label: $t('page.common.Model'),
       defaultValue: '',
      rules: 'required',
      componentProps: {
        options: carModelOptions,
        placeholder: $t('page.common.Please Select')+' '+$t('page.common.Model'),
        class: 'w-full',
      },
    },



    {
      component: 'Select',
      fieldName: 'year',
      label:$t('page.common.Year'),
      rules: 'required',
      componentProps: {
          class: 'w-full',
          placeholder: $t('page.common.Please Select')+' '+$t('page.common.Year'),
          options:year,
      },
    },  

    {
      component: 'Select',
      fieldName: 'config',
      label: $t('page.common.Config'),
      componentProps: {
          class: 'w-full',
          placeholder: $t('page.common.Please Select')+' '+$t('page.common.Config'),
          options:config,
      },
    },  

    // {
    //   component: 'Select',
    //   fieldName: 'config',
    //   label: `${routeTitle}配置`,
    //    componentProps: {
    //       class: 'w-full',
    //       clearable: true,  // 使 Select 可清除
    //       placeholder: '请选择配置',
    //       options:[
    //                 {'label':'','value':''},
    //                 {'label':'EPS','value':'EPS'},
    //                 {'label':'PreminumE','value':'Preminum'},
    //               ],
    //     },
    // },
    {
      component: 'Upload',
      defaultValue: [],
      componentProps: {
        placeholder: $t('page.common.Please Enter'),

      },
    
      fieldName: 'thumbnails',
      label: $t('page.common.Thumbnail'),
    },
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: '请输入亮点，换行表示不同点',
        style: {
          minHeight: '200px' // 设置最低高度
        }
      },
      fieldName: 'highlights',
      label: $t('page.common.Highlight Settings'),
    },

     {
      component: 'Select',
      fieldName: 'smart',
      label: `Smart App`,
      defaultValue: '',
      componentProps: {
          class: 'w-full',
          placeholder: '',
          options:[
                  { label: 'Yes', value: 1 },
                  { label: 'No', value: 0 }
          ],
        },
    },
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'Engine',
      label: 'Engine',
    },

    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'Ground',
      label: 'Ground/Clearance',
    },

    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'Passenger',
      label: 'Passenger/Allowed',
    },

    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'Drive',
      label: 'Drive Train',
    },

    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'Features',
      label: 'Features',
    },

    {
      component: 'Editor',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'post_content',
      label: $t('page.common.Content'),
    },

  ],
});


const [SeoForm, SeoFormApi] = useVbenForm({
  handleSubmit: onSubmit,

  schema: [
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'seo_title',
      label: 'SEO '+$t('page.common.Title'),
      dependencies: {
        trigger: (value) => {
          state.form.post_excerpt = value.post_excerpt;
          state.form.post_keywords = value.post_keywords;
          state.form.more.seo_title = value.seo_title;
          state.form.more.seo_keywords = value.seo_keywords;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'seo_title',
          'seo_keywords',
          'post_excerpt',
          'post_keywords',
        ],
      },
    },
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'seo_keywords',
      label: 'SEO '+$t('page.common.Keywords'),
    },
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'post_excerpt',
      label: 'SEO ' +$t('page.common.Description'),
    },
    {
      component: 'Select',
      defaultValue: [],
      fieldName: 'post_keywords',
      label: $t('page.common.Tags'),
    },
  ],
});

const [TemplateForm, TemplateFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },

      fieldName: 'post_hits',
      label: $t('page.common.Views'),
      dependencies: {
        trigger: (value) => {
          state.form.more.is_payread = value.is_payread;
          state.form.more.price = value.price;
          state.form.more.template = value.template;
          state.form.more.is_jump = value.is_jump;
          state.form.more.is_slide = value.is_slide;
          state.form.more.jump_url = value.jump_url;
          state.form.is_top = value.is_top;
          state.form.recommended = value.recommended;
          state.form.post_hits = value.post_hits;
          state.form.post_source = value.post_source;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'post_hits',
          'post_source',
          'is_top',
          'recommended',
          'is_jump',
          'is_slide',
          'is_payread',
          'price',
          'jump_url',
          'template',
        ],
      },
    },
    {
      component: 'Input',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'post_source',
      label: $t('page.common.Source'),
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
      fieldName: 'is_top',
      label: $t('page.common.Top'),
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
      },
      fieldName: 'recommended',
      label: $t('page.common.Recommended'),
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: '1',
        unCheckedValue: '0',
      },
      fieldName: 'is_jump',
      label: $t('page.common.Redirect'),
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: '1',
        unCheckedValue: '0',
      },
      fieldName: 'is_slide',
      label: $t('page.common.Slideshow'),
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: '1',
        unCheckedValue: '0',
      },
      fieldName: 'is_payread',
      label: $t('page.common.Paid Reading'),
    },
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        show(values) {
          return values.is_payread;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['is_payread'],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'price',
      label: `价格`,
    },
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        show(values) {
          return values.is_jump;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: ['is_jump'],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'jump_url',
      label: `跳转地址`,
    },
    {
      component: 'Select',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Select'),
      },
      fieldName: 'template',
      label: '文章模板',
    },
  ],
});

async function onSubmit() {
  function showMsg(msg: string) {
    message.success(msg);
    closeCurrentTab();
    router.push('/portal/adminarticle/product'); // 跳转到产品 Tab，比如指定页面

  } 
  const values: any = state.form;

  if (values.id ) {
    const { msg } = await putArticle(values);
    showMsg(msg);
  } else {
    delete values.id;
    const { msg } = await postArticle(values);
    showMsg(msg);
  }
}

async function onGetArticle(id: number, code: string) {

   const [data_res, data_year,data_config] = await Promise.all([
    getArticleInfo({ id, code }),
     getYears(),
     getConfigs(),
  ]);
 

  const data  = data_res.data;




  year.value = [
    { label: '请选择年份', value: 0 },
    ...data_year.data.list.map(item => ({ label: item.year, value: item.id }))
  ];

   config.value = [
    { label: '请选择配置', value: '' },
    ...data_config.data.list.map(item => ({ label: item.name, value: item.id }))
  ];

  
  data.post = {
    id: copyFrom!=-1?0:(data.post?.id ?? ''),
    post_title: data.post?.post_title ?? '',
    // slug: data.post?.slug ?? '',
    post_status:data.post?.post_status ?? '',
    post_content: data.post?.post_content ?? '',
    post_keywords: data.post?.post_keywords ?? [],
    post_excerpt: data.post?.post_excerpt ?? '',
    post_hits: data.post?.post_hits ?? 0,
    post_source: data.post?.post_source ?? '',
    published_time:
    data.post?.published_time ?? dayjs().format('YYYY-MM-DD HH:mm:ss'),
    is_top: data.post?.is_top,
    recommended: data.post?.recommended,
    thumbnails: data.post?.thumbnails || [],
    thumbnail: data.post?.thumbnail ?? '',
    categories: data.post?.categories ?? [],
    car_model:data.post?.car_model??'',
    year: data.post?.year ?? '',
    config:data.post?.config??'',
    smart:data.post?.smart??'',
    highlights:data.post?.highlights??'',
    more: {
      seo_title: data.post?.more?.seo_title ?? '',
      seo_keywords: data.post?.more?.seo_keywords ?? '',
      thumbnail: data.post?.more?.thumbnail ?? '',
      template: data.post?.more?.template ?? '',
      is_slide: data.post?.more?.is_slide,
      is_jump: data.post?.more?.is_jump,
      is_watermark: data.post?.more?.is_watermark ?? false,
      jump_url: data.post?.more?.jump_url ?? '',
      Engine: data.post?.more?.Engine,
      Ground: data.post?.more?.Ground,
      Passenger: data.post?.more?.Passenger,
      Drive: data.post?.more?.Drive,
      Features: data.post?.more?.Features,
      price: data.post?.more?.price ? Number.parseInt(data.post.more.price) : 0,
      associationids: data.post?.more?.associationids ?? [],
    },
    attributes: data.post?.attributes,
  };
  if(data.post.categories){
       onCategoryChange(data.post.categories)
  }

  state.form = data.post;
 
  BasicFormApi.setValues({ ...state.form, ...state.form.more });
  SeoFormApi.setValues({ ...state.form, ...state.form.more });
  TemplateFormApi.setValues({ ...state.form, ...state.form.more });
  state.categoriesTree = data.categoryTree;
  state.attributes = data.post?.attributes;
  state.tags = data.tags;
  state.articleThemeFiles = data.articleThemeFiles;
}


const [AttributesModal, AttributesModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: AttributesModalView,
  onClosed() {
    const { attributes, isUpdata } = AttributesModalApi.getData();
    if (isUpdata) {
      const moduleAttributes = mergeObjects(
        state.attributes.module,
        attributes,
        [
          'id',
          'name',
          'type',
          'status',
          'value',
          'options',
          'title',
          'module_id',
        ],
        'name',
      );
      if (state.form.attributes?.module)
        state.form.attributes.module = moduleAttributes;

      state.attributes.module = moduleAttributes;
    }
  },
});
const handleExtra = () => {
  AttributesModalApi.setState({
    title: $t('page.common.Attribute Settings'),
  });

  AttributesModalApi.setData({ module: state.attributes.module });

  AttributesModalApi.open();
};

const [AttributesDrawer, AttributesDrawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: AttributesDrawerView,

  onBeforeClose: () => {
    const drawerData = AttributesDrawerApi.getData();
    const specAttributes = drawerData.specs;
    state.attributes.spec = specAttributes;
  },
});
const handleAttributesDrawer = (
  title: string = '参数设置',
  type: AttriButesType = 'parameter',

) => {
  AttributesDrawerApi.setState({
    title,
  });
  AttributesDrawerApi.setData({
    groups: state.attributes.parameter,
    post_id: index.value,
    specs: state.attributes.spec,
    type,
  });
  console.log('state.attributes.spec',state.attributes.spec)
  AttributesDrawerApi.open();
};

const addItem = (e: any) => {
  e.preventDefault();
  state.tags.push({ name: name.value });
  name.value = '';
  setTimeout(() => {
    inputRef.value?.focus();
  }, 0);
};
onMounted(async () => {
  await onGetArticle(index.value, code.value);
  
});
</script>

<template>
  <Page>
    <AttributesModal />
    <AttributesDrawer />
    <Card :title="$t('page.menu.'+routeTitle)+$t('page.common.Details')">
      <template #extra>
        <Button class="mr-4" type="primary" @click="handleExtra()">
          {{$t('page.common.Attribute Settings')}}
        </Button>
        <Button
          class="mr-4" 
          type="primary"
          @click="handleAttributesDrawer($t('page.common.Parameter Settings'), 'parameter')"
        >
          {{$t('page.common.Parameter Settings')}}
        </Button>
        <Button
          class="mr-4"
          type="primary"
          @click="handleAttributesDrawer($t('page.common.Specification Settings'), 'spec')"
        >
          {{$t('page.common.Specification Settings')}}
        </Button>
      </template>
      <Tabs v-model:active-key="activeKey">
        <TabPane key="1" force-render :tab="$t('page.common.Basic Information')">
          <BasicForm>
            <template #categories="slotProps">
              <TreeSelect
                v-bind="slotProps"
                :field-names="{
                  value: 'id',
                  key: 'id',
                  label: 'name',
                  children: 'children',
                }"
                :tree-data="state.categoriesTree"
                allow-clear
                placeholder="选择车系"
                style="width: 100%"
                tree-default-expand-all
                tree-node-filter-prop="label"
              />
            </template>


          

        
          </BasicForm>
        </TabPane>
        <TabPane key="2" :disabled="disabled" :tab="$t('page.common.SEO Settings')">
          <SeoForm>
            <template #post_keywords="slotProps">
              <Select
                v-bind="slotProps"
                :max-tag-count="3"
                :options="state.tags.map((item) => ({ value: item.name }))"
                mode="multiple"
                style="width: 300px"
              >
                <template #dropdownRender="{ menuNode: menu }">
                  <VNodes :vnodes="menu" />
                  <Divider style="margin: 4px 0" />
                  <Space style="padding: 4px 8px">
                    <Input
                      ref="inputRef"
                      v-model:value="name"
                      placeholder="请输入标签名称"
                    />
                    <Button type="text" @click="addItem">
                      <template #icon>
                        <span class="anticon">
                          <Icon icon="ri:add-line" />
                        </span>
                      </template>
                      {{$t("page.common.Add")}}{{$t("page.common.Tags")}}
                    </Button>
                  </Space>
                </template>
              </Select>
            </template>
          </SeoForm>
        </TabPane>

        <TabPane key="3" :disabled="disabled" :tab="$t('page.common.Other Options')" >
          <TemplateForm>
            <template #template="slotProps">
              <Select v-bind="slotProps" style="width: 100%">
                <SelectOption
                  v-for="item in state.articleThemeFiles"
                  :key="item.id"
                  :value="item.file"
                >
                  {{ `${item.name} ${item.file}` }}
                </SelectOption>
              </Select>
            </template>
          </TemplateForm>
        </TabPane>
   
  
      </Tabs>
    </Card>
  </Page>
</template>
